import React, { useEffect, useMemo, useState } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import {
    NavBar,
    Collapse,
    List,
    Popup,
    Steps,
    Checkbox,
    Card,
    Toast,
    Tag,
    Button,
} from "antd-mobile";

import http from "../../axios/api";

import { useSelector, useDispatch } from "react-redux";
import { updateRiderList } from "../../store/riderListSclice";
import { SubmitBar } from 'react-vant'

function OrderList() {
    const [params] = useSearchParams();
    const id = params.get("id");
    const price = params.get("price");
    const type = params.get("type");
    const [info, setInfo] = useState({});
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const [visible1, setVisible1] = useState(false);
    // 新增倒计时状态
    const [countdown, setCountdown] = useState(30 * 60); // 30分钟，单位秒

    const { state } = useLocation();

    const riderListSlice = useSelector((state) => state.riderListSlice);

    const handlepay = async () => {
        const res = await http.get('/api/pay', {
            params: {
                title: "订单支付",
                id: Math.random().toString(36),
                price,
            }
        });
        const { data } = res.data;

        const payWindow = window.open(data, '_blank');        
        const checkPayWindow = setInterval(() => {
            if (payWindow.closed) {
                clearInterval(checkPayWindow);
                navigate('/orderL?id=' + id);
            }
        }, 1000);
    };


    const getDetials = async () => {
        const res = await http.get(`/api/trip/train/detail?id=${id}`);
        const { code, data } = res.data;
        if (code == 200) {
            setInfo(data);
        }
    };

    useEffect(() => {
        getDetials();
    }, []);

    // 倒计时效果实现
    useEffect(() => {
        if (countdown <= 0) return;

        const timer = setInterval(() => {
            setCountdown(prev => {
                if (prev <= 1) {
                    clearInterval(timer);
                    // 倒计时结束可以添加跳转或提示
                    Toast.show('订单已超时');
                    navigate('/'); // 跳转到首页或其他页面
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

        return () => clearInterval(timer);
    }, [countdown, navigate]);

    const selectProsen = useMemo(() => {
        return riderListSlice.filter((v) => v.status);
    }, [riderListSlice]);

    // 格式化倒计时为分:秒格式
    const formatCountdown = () => {
        const minutes = Math.floor(countdown / 60);
        const seconds = countdown % 60;
        return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    };

    const columnsSelectArr = ["A", "B", "C", "E", "F"];
    const [selectSeat, setSelectSeat] = useState([]);

    const onSubmit = () => {
        if (selectProsen.length != selectSeat.length) {
            Toast.show("请选择座位");
            return;
        }
        setVisible1(true);
    };

    return (
        <div>
            <NavBar>订单</NavBar>

            {/* 显示倒计时 */}
            <div>
                请在{formatCountdown()}内完成支付
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '16px' }}>
                <div>
                    <div>{info.start}</div>
                    <div >{"10:00"}</div>
                    <div>09-09 周五</div>
                </div>
                <div >
                    <div>G103</div>
                    <div>耗时 5时38分</div>
                </div>
                <div>
                    <div>{info.end}</div>
                    <div >11:58</div>
                    <div>09-09 周五</div>
                </div>
            </div>

            <div>
                <h2>退票</h2>
                <List>
                    {selectProsen.map((item, index) => (
                        <List.Item key={item.id}>
                            {item.name}
                            <Checkbox
                                checked={item.status}
                                onChange={(val) => {
                                    dispatch(
                                        updateRiderList({
                                            index,
                                            checked: val,
                                        })
                                    );
                                }}
                            />
                        </List.Item>
                    ))}
                </List>

                <List>
                    <h2>原订单</h2>
                    <div style={{ color: '#ccc', padding: '16px' }}>
                        王五 <Checkbox checked={false} />
                    </div>
                </List>
            </div>

            <Card title="选择座位">
                {selectProsen.map((row, rowIndex) => (
                    <div
                        key={rowIndex}
                        style={{ display: "flex", justifyContent: "space-between", padding: 5 }}
                    >
                        {columnsSelectArr.map((col, colIndex) => (
                            <Tag
                                color={selectSeat.some(v => v.row == rowIndex && v.col == colIndex) ? 'primary' : "default"}
                                key={colIndex}
                                style={{ padding: "10px" }}
                                onClick={() => {
                                    const nSelectSeat = [...selectSeat, { row: rowIndex, col: colIndex }];
                                    if (nSelectSeat.length > selectProsen.length) {
                                        nSelectSeat.shift();
                                    }
                                    setSelectSeat(nSelectSeat);
                                }}
                            >
                                {col}
                            </Tag>
                        ))}
                    </div>
                ))}
            </Card>

            <div>
                <SubmitBar
                    price={price * selectProsen.length * 100}
                    buttonText="提交订单"
                    onSubmit={onSubmit}
                />
            </div>

            <Popup
                visible={visible1}
                onMaskClick={() => setVisible1(false)}
                onClose={() => setVisible1(false)}
                bodyStyle={{ height: '40vh' }}
            >
                <Button onClick={handlepay} block color='primary' size='large'>
                    支付宝
                </Button>
                <Button block color='primary' size='large' style={{ marginTop: '16px' }}>
                    微信
                </Button>
            </Popup>
        </div>
    );
}

export default OrderList;